<template>
  <div class="cart-page">
    <h1>我的购物车</h1>
    <div v-if="isLoading">加载中...</div>
    <el-table v-else :data="cartItems" stripe>
      <el-table-column prop="product_name" label="商品名称"></el-table-column>
      <el-table-column prop="product_price" label="商品价格"></el-table-column>
      <el-table-column prop="quantity" label="数量">
        <template #default="scope">
          <el-input-number v-model="scope.row.quantity" :min="1" @change="updateCartItem(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="subtotal" label="小计"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button @click="removeFromCart(scope.row.cart_id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="checkout-section">
      <el-button type="success" @click="handleCheckout" :disabled="cartItems.length === 0">
        立即结账（总金额：¥{{ totalAmount }}）
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, inject } from 'vue'
import { ElNotification } from 'element-plus'
import axios from 'axios'

const cartItems = ref([])
const isLoading = ref(false)

const fetchCartItems = async () => {
  isLoading.value = true
  try {
    const token = localStorage.getItem('token')
    const userId = localStorage.getItem('userId')
    const response = await axios.get('http://localhost:3000/cart', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    cartItems.value = response.data
  } catch (error) {
    ElNotification({
      title: 'Error',
      message: 'Failed to fetch cart items',
      type: 'error',
    })
    console.error('Error fetching cart items:', error)
  } finally {
    isLoading.value = false
  }
}

onMounted(() => {
  fetchCartItems()
})

const updateCartItem = async (item) => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.put(
      `http://localhost:3000/cart/${item.cart_id}`,
      { itemId: item.item_id,  
        quantity: item.quantity },
      {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }
    )
    const index = cartItems.value.findIndex(cartItem => cartItem.cart_id === item.cart_id)
    if (index !== -1) {
      cartItems.value[index] = response.data
    }
    // 重新获取最新购物车数据
    await fetchCartItems()
    ElNotification({
      title: 'Success',
      message: '购物车项已更新',
      type: 'success',
    })
  } catch (error) {
    ElNotification({
      title: 'Error',
      message: '更新购物车项失败',
      type: 'error',
    })
    console.error('Error updating cart item:', error)
  }
}

const removeFromCart = async (cartId) => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.delete(`http://localhost:3000/cart/${cartId}`, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    cartItems.value = cartItems.value.filter(item => item.cart_id !== cartId)
    ElNotification({
      title: 'Success',
      message: '商品已从购物车中移除',
      type: 'success',
    })
  } catch (error) {
    ElNotification({
      title: 'Error',
      message: '移除购物车项失败',
      type: 'error',
    })
    console.error('Error removing from cart:', error)
  }
}
// 新增计算属性
const totalAmount = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + parseFloat(item.subtotal), 0).toFixed(2)
})

// 获取刷新用户余额的方法
const refreshUserBalance = inject('refreshUserBalance');

// 新增结账方法
const handleCheckout = async () => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.post(
      'http://localhost:3000/orders',
      {},
      {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }
    )
    
    if (response.data.message) {
      // 更新用户余额显示（使用后端返回的最新值）
      const user = JSON.parse(localStorage.getItem('user'))
      user.virtual_currency = response.data.userBalance 
      localStorage.setItem('user', JSON.stringify(user))
      
      ElNotification.success({
        title: '成功',
        message: `订单创建成功，当前余额：¥${response.data.userBalance}`, 
      })
      cartItems.value = []

      // 刷新余额显示
      if (refreshUserBalance) {
        await refreshUserBalance();
      }
    }
  } catch (error) {
    ElNotification.error({
      title: '错误',
      message: error.response?.data?.error || '结账失败',
    })
    console.error('结账失败:', error)
  }
}
</script>

<style scoped>
.cart-page {
  padding: 20px;
}
.checkout-section {
  margin-top: 30px;
  text-align: right;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}
</style>